from flask import Flask, request, jsonify
import os
import configparser

from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler, FileClosedEvent, FileClosedNoWriteEvent
import requests
import threading
import time
import logging
from logging.handlers import RotatingFileHandler
from common import extract_username

app = Flask(__name__)

# 配置日志
handler = RotatingFileHandler('app.log', maxBytes=10000, backupCount=3)
handler.setLevel(logging.INFO)
formatter = logging.Formatter('[%(asctime)s] %(levelname)s in %(module)s: %(message)s')
handler.setFormatter(formatter)
app.logger.addHandler(handler)

# console_handler = logging.StreamHandler()
# console_handler.setLevel(logging.INFO)
# console_handler.setFormatter(formatter)
# app.logger.addHandler(console_handler)

app.logger.setLevel(logging.INFO)

# 读取配置文件
config = configparser.ConfigParser()
config.read('config.ini')
DATA_DIR = config['paths']['data_dir']
REMOTE_URL = config['server']['remote_url']

import os
import re
from datetime import datetime

# 定义文件修改事件处理器
class FileChangeHandler(FileSystemEventHandler):
    # 全局变量，用于存储上次处理文件的时间 （文件的一次修改（包括copy）会触发两次 on_modified，所以需要过滤，只处理第 1次即可）
    # -100 （秒） 是为了防止刚启动时，第一次修改文件还在 10 秒内，也被过滤掉
    last_processed_time = time.time() - 100

    def on_modified(self, event):
        if not event.is_directory:
            app.logger.info(f"on_file_modified: {event.src_path}")
            self.process_file(event.src_path)


    def process_file(self, file_path):
        if not file_path.endswith('.txt'):
            app.logger.debug(f"Skipping non-text file: {file_path}")
            return

        if time.time() - self.last_processed_time < 10:
            app.logger.info(f"current_time = {time.time()}, last_processed_time = {self.last_processed_time}, time diff = {time.time() - self.last_processed_time}, skip")
            return

        app.logger.info(f"current_time = {time.time()}, last_processed_time = {self.last_processed_time}, time.time() - last_processed_time = {time.time() - self.last_processed_time}")
        self.last_processed_time = time.time()
        try:
            with open(file_path, 'r') as f:
                content = f.read()
            if len(content) < 100:
                app.logger.info(f"content too short: {file_path}, ignore it")
                return

            g_username = extract_username(file_path)
            app.logger.info(f"username: {g_username} , content: {content}")
            # 发送HTTP请求
            payload = {
                'username': g_username,
                'text': content
            }
            # app.logger.info('File username: %s', payload.get('username'))  # Proper logging
            # app.logger.info('File content: %s', payload.get('text'))  # Proper logging
            result = requests.post(REMOTE_URL, payload)
            print(f"Successfully send {file_path} to {REMOTE_URL}， result ={ result}")
        except Exception as e:
            app.logger.info(f"Error processing file {file_path}: {e}")

def start_file_monitor():
    # 如果 DATA_DIR 不存在，创建文件夹
    if not os.path.exists(DATA_DIR):
        os.makedirs(DATA_DIR)
        app.logger.info(f"Created directory: {DATA_DIR}")

    event_handler = FileChangeHandler()
    observer = Observer()
    observer.schedule(event_handler, DATA_DIR, recursive=True)
    observer.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()


if __name__ == '__main__':
    # 启动文件监控线程
    monitor_thread = threading.Thread(target=start_file_monitor, daemon=True)
    monitor_thread.start()

    # 启动Flask应用
    app.run(host='0.0.0.0', port=5002)
